﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Najak.RenderControls
{
	public class GameDraw : GraphicsDeviceControl, IAppHost
	{
		private App _game;

		private System.Timers.Timer timerInvalidator;

		protected override void Initialize()
		{
			timerInvalidator = new System.Timers.Timer();
			timerInvalidator.Elapsed += new System.Timers.ElapsedEventHandler(timerInvalidator_Elapsed);
			timerInvalidator.Interval = 10;
			timerInvalidator.AutoReset = true;
			timerInvalidator.Start();

			_game = App.Create(this, null);
			_game.LoadContent();
			_lastUpdateTicks = System.Environment.TickCount;

		}

		private long _timeElapsed;
		private int _lastUpdateTicks;

		private bool _isFirstDraw = true;

		private void OnFirstDraw()
		{
			_isFirstDraw = false;
		}

		protected override void UpdateGameLoop()
		{
			if (_isFirstDraw)
				OnFirstDraw();

			int ticksNow = System.Environment.TickCount;
			int ticksElapsed = ticksNow - _lastUpdateTicks;
			_lastUpdateTicks = ticksNow;
			_timeElapsed += ticksElapsed;

			GameTime gameTime = new GameTime(TimeSpan.FromMilliseconds(_timeElapsed), TimeSpan.FromMilliseconds(ticksElapsed));

			_game.Update(gameTime);
		}
		protected override void Draw()
		{
			_game.Draw();
		}
		private void timerInvalidator_Elapsed(object sender, EventArgs e)
		{
			FrameworkDispatcher.Update();
			Invalidate();
		}


		public Rectangle ScreenArea
		{
			get 
			{
				var area = ClientRectangle;
				return new Rectangle(area.X, area.Y, area.Width, area.Height);
			}
		}

		public Point ScreenLocation
		{
			get
			{
				var p = base.PointToScreen(new System.Drawing.Point());
				return new Point(p.X, p.Y);
			}
		}

		public Point ScreenSize
		{
			get
			{
				var area = ClientRectangle;
				return new Point(area.Width, area.Height);
			}
		}

		public bool IsMousePositionAlreadyCorrect
		{
			get { return false; }
		}
	}
}
